import { createStore } from "vuex"
import api from "@/api/login"
import auth from "@/utils/auth"
import messageInfo from "@/utils/message"

const mockInterfaceList=[
  'admin',
  'editor',
  'user',
  'getUser',
  'login',
  'logout',
  'resetPWD',
  'getMenuList',
  'getInterfaceList',
  'getCaptcha',
  'getUserInfo',
  'forceLogout',
  'statistic/homeChart',
  'category/list',
  'category/tree',
]

const mockMenuList=[
  {
    "id": 1,
    "name": "首页",
    "path": "/home",
    "icon": "el-icon-s-home",
    "children": []
  },
  {
    "id": 2,
    "name": "商品管理",
    "path": "/product",
    "icon": "el-icon-s-goods",
    "children": []
  }
]

const store = createStore({
  state: {
    userInfo: null,
    asideWidth: '250px',
    menuList: [],
    interfaceList:[],
  },
  mutations: {
    setUserInfo(state, payload) {
      state.userInfo = payload
      //浏览器关闭，cookie被清楚了，这里需要通过本地的用户信息重新设置token
      auth.setToken(payload.token)
      LocalStorage.set("userInfo", payload)
    },
    setAsideWidth(state, payload) {
      state.asideWidth = !payload ? '60px' : '250px'
      console.log("asideWidth: ", state.asideWidth)
    },
    setMenuList(state, payload) {
      state.menuList = payload
      console.log("menuList: ", state.menuList)
    },
    setInterfaceList(state, payload) {
      state.interfaceList = payload
      console.log("interfaceList: ", state.interfaceList)
    }
  },
  actions: {

    //更新mutations 中的用户信息数据
    getUserInfo(context, payload) {
      // console.log("context: ", context)
      // console.log("getUserInfo-payload: ", payload)
      let userInfo = LocalStorage.get("userInfo")
      console.log("userInfo: ", userInfo)
      let user={...userInfo}
      user.menuList=userInfo?.menuList?userInfo.menuList:[];
      user.interfaceList=userInfo?.interfaceList?userInfo.interfaceList:mockInterfaceList;
      if(userInfo){
        context.commit('setUserInfo', user)
        context.commit("setMenuList",user.menuList)
        context.commit("setInterfaceList",user.interfaceList)
        return user
      }
      
      //TODO 后期通过请求token获取当前登录用户数据，涉及到需要请求接口，耗时长，这里选择使用localStorage
      // return new Promise((resolve, reject) => {
      //   api.getUser().then(res=>{
      //     console.log("getUserInfo(): res: ", res)
      //     context.commit('setUserInfo', res)
      //     resolve(res)
      //   }).catch(error=>{
      //     console.log("getUserInfo(): error: ", error)
      //     reject(error)
      //   })
      // })
      
    },

    forceLogout(){
      api.logout(auth.getToken()).then(res=>{
        localStorage.clearAll()
        auth.removeToken()
        LocalStorage.remove("userInfo")
        
      }).catch(error=>{
        console.log("getUserInfo(): error: ", error)
        messageInfo.error(error)
      }).finally(()=>{
        window.location.href="/login"
        location.reload()
      })
      
      
    }
  }

})

export default store